package com.zscat.mallplus.util;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zscat.mallplus.dms.entity.DmsOrder;
import com.zscat.mallplus.dms.service.IDmsOrderService;
import com.zscat.mallplus.enums.OrderStatus;
import com.zscat.mallplus.qsg.QsgReport;
import com.zscat.mallplus.qsg.QsgStore;
import com.zscat.mallplus.qsg.service.IQsgStoreService;
import com.zscat.mallplus.qsg.service.IReportService;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.quartz.QuartzJobBean;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;


public class Myquartz extends QuartzJobBean {

    @Autowired
    private IReportService reportService;
    @Autowired
    private IDmsOrderService orderService;
    @Autowired
    private IQsgStoreService storeService;


    @Override
    protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
        //从订单获取今天的订单金额并汇总到汇总表
        List<QsgStore> allStore = storeService.list(new QueryWrapper<>());
        if (null!=allStore&&allStore.size()>0){
            Date now = new Date();
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(now);
            calendar.add(Calendar.DATE, -1);
            //更新前一天数据
            String date = DateUtil.dateToStr(calendar.getTime(),"yyyy-MM-dd");
            for (QsgStore store : allStore){
                Long storeId = store.getId().longValue();
                QueryWrapper<DmsOrder> queryWrapper = new QueryWrapper<DmsOrder>();
                queryWrapper.eq("store_id", storeId);
                List<Integer> statusQw = new ArrayList<>();
                statusQw.add(OrderStatus.HAS_PAYMONEY.getValue());
                statusQw.add(OrderStatus.COMPLETED.getValue());
                queryWrapper.in("order_status", statusQw);
                queryWrapper.ne("integral",0);
                String startTime = date + " 00:00:00";
                String endTime = date + " 23:59:59";
                queryWrapper.le("create_datetime", endTime);
                queryWrapper.ge("create_datetime", startTime);
                int orderNum = orderService.count(queryWrapper);
                queryWrapper.select("sum(price) as allMoney");
                BigDecimal money = BigDecimal.ZERO;
                if (orderNum != 0) {
                    DmsOrder order = orderService.getOne(queryWrapper);
                    money = order.getAllMoney();
                }
                QsgReport report = new QsgReport();
                report.setStoreId(storeId);
                report.setTime(date);
                report.setMoney(money);
                report.setOrderNum(orderNum);
                reportService.save(report);
            }
        }
    }
}
